package com.basketball.task;

import com.basketball.entity.ClubDate;
import com.basketball.entity.Player;
import com.basketball.entity.Remark;
import com.basketball.entity.Skills;
import com.basketball.service.*;
import com.basketball.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 篮球活动发起定时器
 */
@Component
public class BasketBallTask {
    public final static Logger logger = LoggerFactory.getLogger(BasketBallTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private PlayerService playerService;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private MailService mailService;
    @Autowired
    private ClubDateService  clubDateService;
    @Autowired
    private RemarkService remarkService;
    /**
     * 每天下午4点执行
     */
    //@Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 0 16 * * ?")
    private void process() {
        logger.info("报名定时器开始，现在时间：" + dateFormat.format(new Date()));
        String week_index = canPlay2();
        if(week_index!=null){
            sendMail(week_index);
        }
    }

    /**
     * 判断是否为活动日期前一天
     * @return
     */
    private String canPlay() {
        List<ClubDate> list = clubDateService.getAll();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int week_index = calendar.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < list.size(); i++) {
            ClubDate clubDate = list.get(i);
            if(week_index == clubDate.getDate()){
                logger.info(clubDate.getDate()+"明天是星期：" + week_index+ "可以组织活动");
                //返回真实的活动日期的String
                calendar.add(Calendar.DAY_OF_MONTH, -1); //解决周日会出现 并到下一周的情况
                calendar.set(Calendar.DAY_OF_WEEK, week_index+1);
                logger.info("真实的活动日期："  +dateFormat.format(calendar.getTime()));
                return dateFormat.format(calendar.getTime());
            }
            else{
                logger.info(clubDate.getDate()+"明天是星期："  +week_index + "无活动");
            }
        }

        return null;
    }

    /**
     * 修改为返回明天日期
     * @return
     */
    private String canPlay2() {
        List<ClubDate> list = clubDateService.getAll();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int week_index = calendar.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < list.size(); i++) {
            ClubDate clubDate = list.get(i);
            if(week_index == clubDate.getDate()){
                logger.info(clubDate.getDate()+"明天是星期：" + week_index+ "可以组织活动");
                //返回真实的活动日期的String
//                calendar.add(Calendar.DAY_OF_MONTH, -1); //解决周日会出现 并到下一周的情况
//                calendar.set(Calendar.DAY_OF_WEEK, week_index+1);
                calendar.add(Calendar.DATE,1);
                logger.info("真实的活动日期(就是明天嘛）："  +dateFormat.format(calendar.getTime()));
                return dateFormat.format(calendar.getTime());
            }
            else{
                logger.info(clubDate.getDate()+"明天是星期："  +week_index + "无活动");
            }
        }

        return null;
    }



    public void sendMail(String week_index) {
        List<Player> playerList = playerService.getByState();
        List<Remark> remarkList = remarkService.getAllRemarks();
        String remarkInfo ="不要轻言放弃，一旦放弃了，比赛就结束了。——安西教练";
        //获取1-list.size中的随机数
        if(remarkList.size()>0){
           int i = (int)(1+Math.random()*(remarkList.size()-1+1));
            remarkInfo = remarkList.get(i).getRemarkinfo();
        }
        for (int i = 0; i < playerList.size(); i++) {
            Player player =playerList.get(i);
            logger.info("发送【活动报名】邮件给" + player.getName()+"==="+player.getEmail());
            sendTemplateMail(player.getEmail(), player.getName(),week_index,player.getSec(),remarkInfo);
        }
        logger.info("【活动报名】邮件发送完毕" + dateFormat.format(new Date()));
    }


    public void sendTemplateMail(String email, String name,String week_index,String seckey,String remark) {
        logger.info(email, name);
        //创建邮件正文
        Context context = new Context();
        context.setVariable("name", name);
        context.setVariable("week_index", week_index);
        context.setVariable("seckey",seckey);
        context.setVariable("ip", IpUtil.getIpAddress());
        context.setVariable("remark",remark);
        String emailContent = templateEngine.process("playerEmailTemplatenNew", context);
        mailService.sendHtmlMail(email, "活动报名", emailContent);
    }

}
